package cn.maihe.elg.operation.centers.epoint.channel;

import cn.maihe.elg.operation.centers.epoint.channel.service.MeiShanEpointBaohanNoticeChannelService;
import cn.maihe.elg.operation.centers.epoint.channel.service.MeiShanEpointGuarantorClaimSettlementChannelService;
import cn.maihe.elg.operation.centers.epoint.channel.service.MeiShanEpointGuarantorRevokeChannelService;
import cn.maihe.elg.operation.centers.epoint.channel.service.MeiShanGiveupNoticeChannelService;
import cn.maihe.elg.operation.centers.epoint.channel.service.MeiShanInvoiceNoticeChannelService;
import cn.maihe.elg.operation.centers.epoint.channel.service.MeiShanUploadBaohanFileChannelService;
import cn.maihe.elg.operation.centers.epoint.channel.service.MeiShancClaimSrePayNoticeChannelService;
import cn.maihe.elg.operation.centers.epoint.dto.EpointBaseRespDTO;
import cn.maihe.elg.operation.centers.epoint.dto.channel.MeiShanEpointBaohanNoticeReqDTO;
import cn.maihe.elg.operation.centers.epoint.dto.channel.MeiShanEpointGuaranteeClaimSettlementReqDTO;
import cn.maihe.elg.operation.centers.epoint.dto.channel.MeiShanEpointGuaranteeRevokeReqDTO;
import cn.maihe.elg.operation.centers.epoint.enums.EpointRespCodeEnum;
import cn.maihe.elg.operation.centers.supports.model.bo.GuaranteeClaimSettlementResultBo;
import cn.maihe.elg.operation.centers.supports.model.bo.GuaranteeRevokeResultBo;
import cn.maihe.elg.operation.centers.supports.model.bo.InnerUploadBaohanFileBo;
import cn.maihe.elg.operation.centers.supports.model.bo.NoticeGuaranteeApplyResultBo;
import cn.maihe.elg.operation.centers.supports.model.bo.NoticePayResultBo;
import cn.maihe.elg.operation.centers.supports.model.bo.PushCenterGuaranteeBo;
import cn.maihe.elg.operation.model.dto.InnerBaseResp;
import cn.maihe.elg.operation.model.enums.CenterNoEnum;
import cn.maihe.elg.operation.model.enums.RefundOrderStatus;
import cn.maihe.elg.operation.repository.entity.AcceptOrderInfoDO;
import cn.maihe.elg.operation.repository.entity.BidCustomerDO;
import cn.maihe.elg.operation.repository.entity.GuaranteeDO;
import cn.maihe.elg.operation.repository.entity.GuaranteeVo;
import cn.maihe.elg.operation.repository.entity.ProjectInfoDO;
import cn.maihe.elg.operation.repository.entity.RefundOrderAttachmentDO;
import cn.maihe.elg.operation.repository.entity.RefundOrderAttachmentDOCondition;
import cn.maihe.elg.operation.repository.entity.RefundOrderInfoDO;
import cn.maihe.elg.operation.service.business.BidCustomerService;
import cn.maihe.elg.operation.service.business.ProjectInfoService;
import cn.maihe.elg.operation.service.guarantee.GuaranteeService;
import cn.maihe.elg.operation.service.order.AcceptOrderInfoService;
import cn.maihe.elg.operation.service.order.RefundOrderAttachmentService;
import cn.maihe.elg.operation.utils.DateUtil;
import cn.maihe.elg.operation.utils.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * @Description 眉山（新点）对接中心
 * @Author SSX
 * @Date 2025/07/04
 */
@Service
@Slf4j
public class MeiShanEpointCenterInterfaceServiceImpl extends BaseEpointCenterInterfaceService {

    @Resource
    private AcceptOrderInfoService acceptOrderInfoService;
    @Resource
    private ProjectInfoService projectInfoService;
    @Resource
    private BidCustomerService bidCustomerService;
    @Resource
    private GuaranteeService guaranteeService;
    @Resource
    private MeiShanEpointBaohanNoticeChannelService meiShanEpointBaohanNoticeChannelService;
    @Resource
    private MeiShanUploadBaohanFileChannelService meiShanUploadBaohanFileChannelService;
    @Resource
    private MeiShanInvoiceNoticeChannelService meiShanInvoiceNoticeChannelService;
    @Resource
    private MeiShancClaimSrePayNoticeChannelService meiShancClaimSrePayNoticeChannelService;
    @Resource
    private MeiShanGiveupNoticeChannelService meiShanGiveupNoticeChannelService;
    @Resource
    private MeiShanEpointGuarantorRevokeChannelService meiShanEpointGuarantorRevokeChannelService;
    @Resource
    private MeiShanEpointGuarantorClaimSettlementChannelService meiShanEpointGuarantorClaimSettlementChannelService;

    @Resource
    RefundOrderAttachmentService refundOrderAttachmentService;

    @Override
    public CenterNoEnum getCenterNoEnum() {
        return CenterNoEnum.MEISHAN;
    }

    @Override
    public InnerBaseResp<NoticeGuaranteeApplyResultBo> noticePayResult(NoticePayResultBo bo) {
        return InnerBaseResp.success(null, "无需 电子保函支付结果通知");
    }

    @Override
    public InnerBaseResp<String> pushGuarantee(PushCenterGuaranteeBo bo) {
        GuaranteeVo vo = bo.getGuaranteeVo();
        AcceptOrderInfoDO acceptOrderInfo = acceptOrderInfoService.getByAcceptOrderNo(vo.getAcceptOrderNo());
        Assert.notNull(acceptOrderInfo, "查无此受理订单记录");
        BidCustomerDO bidCustomerDO = bidCustomerService.selectById(acceptOrderInfo.getBidCustomerId());
        Assert.notNull(bidCustomerDO, "查无此投保客户信息");

        MeiShanEpointBaohanNoticeReqDTO reqDTO = new MeiShanEpointBaohanNoticeReqDTO();
        reqDTO.setApplyno(vo.getCenterOrderId());
        reqDTO.setBaohanno(vo.getGuaranteeNo());
        reqDTO.setPayername(vo.getBidCustomerName());
        reqDTO.setPayeraccount(bidCustomerDO.getLicenseAccount());
        reqDTO.setInstname(vo.getGuarantorName());
        reqDTO.setGeneratetime(DateUtil.formateDate(acceptOrderInfo.getGuaranteeTime(), "yyyy-MM-dd HH:mm:ss"));
        //0.01% 转0.0001
        reqDTO.setRate(getPercentageToDecimal(vo.getRate()));
        reqDTO.setCost(fen2yuanString(Long.valueOf(vo.getAmount())));
        reqDTO.setApplystatus(bo.getApplyStatus());

        InnerBaseResp<String> innerBaseResp = null;

        try {
            EpointBaseRespDTO resp = meiShanEpointBaohanNoticeChannelService.doRequest(getCenterNoEnum(), reqDTO);
            if (EpointRespCodeEnum.isSuccess(resp.getCode())) {
                innerBaseResp = InnerBaseResp.success(reqDTO.getBaohanno());
            } else {
                innerBaseResp = InnerBaseResp.error(resp.getMessage());
            }
        } catch (Exception e) {
            log.error("开函结果通知 >> [{}] 异常:{}", getCenterNoEnum().getCenterName(), e.getMessage(), e);
            innerBaseResp = InnerBaseResp.error("通知异常:" + e.getMessage());
        }

        return innerBaseResp;
    }

    @Override
    public InnerBaseResp uploadBaohanFile(String acceptOrderNo, InnerUploadBaohanFileBo bo) {
        return meiShanUploadBaohanFileChannelService.uploadBaohanFile(acceptOrderNo, getCenterNoEnum(), bo);
    }

    /**
     * 电子发票结果通知 InvoiceNotice
     */
    @Override
    public InnerBaseResp<EpointBaseRespDTO> invoiceResultNotify(String acceptOrderNo) {
        return meiShanInvoiceNoticeChannelService.invoiceResultNotify(acceptOrderNo);
    }

    /**
     * 追偿结果通知
     */
    public InnerBaseResp<EpointBaseRespDTO> claimSrePayNotice(GuaranteeClaimSettlementResultBo bo) {
        return meiShancClaimSrePayNoticeChannelService.claimSrePayNotice(getCenterNoEnum(),bo);
    }

    /**
     * 追偿结果通知
     */
    public InnerBaseResp<EpointBaseRespDTO> giveupNotice(String acceptOrderNo) {
        return meiShanGiveupNoticeChannelService.giveupNotice(getCenterNoEnum(),acceptOrderNo);
    }

    @Override
    public InnerBaseResp noticeGuaranteeRevokeResult(GuaranteeRevokeResultBo bo) {
        MeiShanEpointGuaranteeRevokeReqDTO reqDTO = new MeiShanEpointGuaranteeRevokeReqDTO();
        reqDTO.setApplyno(bo.getCenterOrderId());
        reqDTO.setBaohanno(bo.getGuaranteeNo());
        if(bo.getAuditPass()){
            reqDTO.setApplystatus("1");
            reqDTO.setTuibaotime(DateUtil.getCurrentDate(DateUtil.FORMAT_DATETIME));
        }else {
            reqDTO.setApplystatus("0");
        }

        GuaranteeDO guarantee = guaranteeService.getGuaranteeByGuaranteeNo(reqDTO.getBaohanno());
        Assert.notNull(guarantee, "查无此保函记录");

        InnerBaseResp<String> innerBaseResp = null;
        try {
            EpointBaseRespDTO resp = meiShanEpointGuarantorRevokeChannelService.doRequest(getCenterNoEnum(), reqDTO);
            if (EpointRespCodeEnum.isSuccess(resp.getCode())) {
                //保函编号作为序列号
                innerBaseResp = InnerBaseResp.success(reqDTO.getBaohanno());
            } else {
                innerBaseResp = InnerBaseResp.error(resp.getMessage());
            }
        } catch (Exception e) {
            log.error("保函撤销|退保结果通知 >> [{}] 异常:{}", getCenterNoEnum().getCenterName(), e.getMessage(), e);
            innerBaseResp = InnerBaseResp.error("通知异常:" + e.getMessage());
        }
        return innerBaseResp;
    }

    @Override
    public InnerBaseResp noticeGuaranteeClaimSettlementResult(GuaranteeClaimSettlementResultBo bo) {
        MeiShanEpointGuaranteeClaimSettlementReqDTO reqDTO = new MeiShanEpointGuaranteeClaimSettlementReqDTO();
        RefundOrderInfoDO refundOrderInfo = bo.getRefundOrderInfo();
        //原理赔申请接口中的 业务流水号
        reqDTO.setApplyno(refundOrderInfo.getRefundOrderNo());
        reqDTO.setBaohanno(refundOrderInfo.getGuaranteeNo());

        ProjectInfoDO projectInfoDO = projectInfoService.selectById(refundOrderInfo.getProjectId());
        //赔付状态，1待赔付2已赔付3不予赔付9其他
        if (refundOrderInfo.getStatus() == RefundOrderStatus.UNREFUND.getStatus() ||
                refundOrderInfo.getStatus() == RefundOrderStatus.APPROVAL.getStatus()
        ) {
            reqDTO.setCompensatestatus("1");
        } else if (refundOrderInfo.getStatus() == RefundOrderStatus.REFUNDED.getStatus()) {
            reqDTO.setCompensatestatus("2");
        } else if (refundOrderInfo.getStatus() == RefundOrderStatus.REFUSED.getStatus()) {
            reqDTO.setCompensatestatus("3");
        } else {
            reqDTO.setCompensatestatus("9");
        }
        reqDTO.setCompensateremark(refundOrderInfo.getRemark());

        if (refundOrderInfo.getStatus() == RefundOrderStatus.REFUNDED.getStatus()) {
            reqDTO.setCompensatedate(DateUtil.formateDate(refundOrderInfo.getCompensateDate(), DateUtil.FORMAT_DATETIME));
            reqDTO.setCompensateway(refundOrderInfo.getCompensateWay().toString());
            reqDTO.setTransferdate(DateUtil.formateDate(refundOrderInfo.getTransferDate(), DateUtil.FORMAT_DATETIME));
            String refundAmount = refundOrderInfo.getPayerAmount();
            String amount = StringUtils.isBlank(refundAmount) ? StringUtil.toYuan(refundOrderInfo.getBidBond())
                    : refundAmount;
            reqDTO.setCompensateamount(amount);
            JSONArray fileurls = new JSONArray();
            RefundOrderAttachmentDO refundOrderAttachmentDO = refundOrderAttachmentService.selectOne(RefundOrderAttachmentDOCondition.builder().andRefundOrderIdEq(refundOrderInfo.getId()).andBusinessTypeEq(2).build());
            JSONObject fileurl = new JSONObject();
            fileurl.put("fileurl",refundOrderAttachmentDO.getFileUrl());
            fileurls.add(fileurl);
            reqDTO.setTransferfilelist(fileurls.toJSONString());
        }

        InnerBaseResp<String> innerBaseResp = null;
        try {
            EpointBaseRespDTO resp = meiShanEpointGuarantorClaimSettlementChannelService.doRequest(getCenterNoEnum(), reqDTO);
            if (EpointRespCodeEnum.isSuccess(resp.getCode())) {
                innerBaseResp = InnerBaseResp.success(reqDTO.getBaohanno());
            } else {
                innerBaseResp = InnerBaseResp.error(resp.getMessage());
            }
        } catch (Exception e) {
            log.error("理赔结果通知 >> [{}] 异常:{}", getCenterNoEnum().getCenterName(), e.getMessage(), e);
            innerBaseResp = InnerBaseResp.error("通知异常:" + e.getMessage());
        }

        if(innerBaseResp.getRespCode().isSuccess() && CenterNoEnum.MEISHAN.equals(getCenterNoEnum())){
            try {
                meiShancClaimSrePayNoticeChannelService.claimSrePayNotice(getCenterNoEnum(),bo);
            } catch (Exception e) {
                log.error("追偿结果通知>> [{}] 异常:{}", getCenterNoEnum().getCenterName(), e.getMessage(), e);
            }
        }

        return innerBaseResp;
    }
}
